package com.fh.common.exception;

import com.fh.common.api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author Qiu,Junda 
 * @date 2019年3月20日
 * @description 异常处理器
 */
@RestControllerAdvice
@Slf4j
public class SelfDefinedExceptionHandler {
	
	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(SelfDefinedException.class)
	public Result<?> handleSelfException(SelfDefinedException e){
		log.error(e.getMessage());
		return Result.error(e.getMessage());
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public Result<?> handlerNoFoundException(Exception e) {
		log.error(e.getMessage());
		return Result.error(404, "路径不存在，请检查路径是否正确");
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public Result<?> handleDuplicateKeyException(DuplicateKeyException e){
		log.error(e.getMessage());
		return Result.error("数据库中已存在该记录");
	}
	
	@ExceptionHandler(AuthenticationException.class)
	public Result<?> handleAuthenticationException(AuthenticationException e){
		log.error(e.getMessage());
		return Result.error("请重新登录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public Result<?> handleAuthorizationException(AuthorizationException e){
		log.error(e.getMessage());
		return Result.error("没有权限，请联系管理员授权");
	}

	@ExceptionHandler(Exception.class)
	public Result<?> handleException(Exception e){
		log.error(e.getMessage(),e);
		return Result.error(e.getMessage());
	}
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
		log.error(e.getMessage(),e);
		StringBuilder sb = new StringBuilder(128);
		for (ObjectError error : e.getBindingResult().getAllErrors()) {
			
			sb.append("[").append(error.getDefaultMessage()).append("] ");
		}
		return Result.error(sb.toString());
	}
}
